package edu.faytechcc.csc.gui.input;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * This class creates a user interface for updating the Anime and Manga tables
 * inside of the Animanga Database.
 *
 * @author Stephanie Mckenzie and Jasmin Pastari
 */
public class InputPanel extends JPanel
{
    // This is how many characters the VARCHAR allows in the table
    private final int UNIQ_ID_MAX = 6;
    private final int ENG_TITLE_MAX = 100;
    private final int JAP_TITLE_MAX = 100;
    private final int DESCRIPTION_MAX = 800;
    private final int NUM_VOL_MAX = 3;
    private final int GENERA_MAX = 200;
    private final int ARTIST_MAX = 100; //or company in the anime table
    private final int PHOTO_MAX = 100;
    // JPanels for holding everything
    private JPanel titlePanel;
    private JPanel buttonPanel;
    private JPanel detailsPanel;
    private JPanel discriptionPanel;
    // JLabels for field discriptions
    private JLabel uniqIdLabel;
    private JLabel englishTitleLabel;
    private JLabel japaneseTitleLabel;
    private JLabel descriptionLabel;
    private JLabel generaLabel;
    private JLabel numberOrVolumesLabel;
    private JLabel artistLabel;
    // Jthings for information input
    private JTextField uniqIdTextField;
    private JTextField englishTitleTextField;
    private JTextField japaneseTitleTextField;
    private JScrollPane areaScrollPane; //scroll pane
    private JTextArea descriptionTextArea; // text area
    private JTextField generaTextField;
    private JTextField numberOrVolumesTextField;
    private JTextField artistTextField;
    // button
    private JButton choosePhotoButton;
    private JButton submitAnimeButton;
    private JButton submitMangaButton;
    // variables
    private String uniqId;
    private String engTitle;
    private String japTitle;
    private String description;
    private String numVol;
    private String genera;
    private String artist; //or company in the anime table
    private String photo = "";

    public InputPanel()
    {
        BuildPanel();
    }

    private void BuildPanel()
    {
        // Add panels for organization
        titlePanel = new JPanel();
        buttonPanel = new JPanel();
        detailsPanel = new JPanel();
        discriptionPanel = new JPanel();
        // Fill the empty variables
        uniqIdLabel = new JLabel("Unique ID: ", JLabel.RIGHT);
        englishTitleLabel = new JLabel("English Title: ", JLabel.RIGHT);
        japaneseTitleLabel = new JLabel("Japanese Title: ", JLabel.RIGHT);
        descriptionLabel = new JLabel("Description: ", JLabel.RIGHT);
        generaLabel = new JLabel("Genera: ", JLabel.RIGHT);
        numberOrVolumesLabel = new JLabel("Number of Volumes/Episodes: ", JLabel.RIGHT);
        artistLabel = new JLabel("Artist or Production Company: ", JLabel.RIGHT);

        uniqIdTextField = new JTextField(UNIQ_ID_MAX);
        englishTitleTextField = new JTextField(10);
        japaneseTitleTextField = new JTextField(10);

        descriptionTextArea = new JTextArea(7, 30);
        descriptionTextArea.setLineWrap(true);
        areaScrollPane = new JScrollPane(descriptionTextArea);
        areaScrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        areaScrollPane.setPreferredSize(new Dimension(300, 120));

        generaTextField = new JTextField(10);
        numberOrVolumesTextField = new JTextField(10);
        artistTextField = new JTextField(10);

        choosePhotoButton = new JButton("Add Image");
        submitAnimeButton = new JButton("Submit to Anime Table");
        submitMangaButton = new JButton("Submit to Manga Table");

        // Add to Title Panel
        titlePanel.add(uniqIdLabel);
        titlePanel.add(uniqIdTextField);
        titlePanel.add(englishTitleLabel);
        titlePanel.add(englishTitleTextField);
        titlePanel.add(japaneseTitleLabel);
        titlePanel.add(japaneseTitleTextField);
        // Add to Button Panel
        buttonPanel.add(choosePhotoButton);
        buttonPanel.add(submitAnimeButton);
        buttonPanel.add(submitMangaButton);
        choosePhotoButton.addActionListener(new PhotoButtonActionListener());
        submitAnimeButton.addActionListener(new SubmitButtonActionListener("Anime"));
        submitMangaButton.addActionListener(new SubmitButtonActionListener("Manga"));
        // Add to Discription Panel
        discriptionPanel.add(descriptionLabel);
        discriptionPanel.add(areaScrollPane);
        // Add to Details Panel
        JPanel layoutPanel = new JPanel();
        layoutPanel.setLayout(new GridLayout(3, 2, 5, 5));
        layoutPanel.add(generaLabel);
        layoutPanel.add(generaTextField);
        layoutPanel.add(numberOrVolumesLabel);
        layoutPanel.add(numberOrVolumesTextField);
        layoutPanel.add(artistLabel);
        layoutPanel.add(artistTextField);
        // Details Panel Layout
        detailsPanel.setLayout(new BorderLayout());
        Dimension size = new Dimension(0, 20);
        detailsPanel.add(Box.createRigidArea(size), BorderLayout.NORTH);
        detailsPanel.add(Box.createRigidArea(size), BorderLayout.SOUTH);
        detailsPanel.add(layoutPanel, BorderLayout.CENTER);
        // Add to Main Panel
        this.setLayout(new BorderLayout());
        this.add(titlePanel, BorderLayout.NORTH);
        this.add(buttonPanel, BorderLayout.SOUTH);
        this.add(discriptionPanel, BorderLayout.EAST);
        this.add(detailsPanel, BorderLayout.CENTER);
    }

    /**
     * Checks the length of the input and returns a String on which do not match
     * or "GOOD" when all fields lengths are acceptable
     *
     * @return
     */
    private String CheckValidInput()
    {
        this.uniqId = uniqIdTextField.getText();
        this.engTitle = englishTitleTextField.getText();
        this.japTitle = japaneseTitleTextField.getText();
        this.description = descriptionTextArea.getText();
        this.genera = generaTextField.getText();
        this.numVol = numberOrVolumesTextField.getText();
        this.artist = artistTextField.getText();

        if (uniqId.length() != UNIQ_ID_MAX)
        {
            return "UNIQ ID should be " + UNIQ_ID_MAX;
        } else if (engTitle.length() > ENG_TITLE_MAX)
        {
            return "English Title should be less than " + ENG_TITLE_MAX;
        } else if (japTitle.length() > JAP_TITLE_MAX)
        {
            return "Japanese Title should be less than " + JAP_TITLE_MAX;
        } else if (description.length() > DESCRIPTION_MAX)
        {
            return "Description should be less than " + DESCRIPTION_MAX;
        } else if (genera.length() > GENERA_MAX)
        {
            return "Genera's should be less than " + GENERA_MAX;
        } else if (numVol.length() > NUM_VOL_MAX)
        {
            return "Number of Volumes or Episodes s should be less than less than 1000";
        } else if (artist.length() > ARTIST_MAX)
        {
            return "Artist should be less than " + ARTIST_MAX;
        } else
        {
            return "GOOD";
        }
    }

    private class PhotoButtonActionListener implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            JFileChooser fileChooser = new JFileChooser();
            int status = fileChooser.showOpenDialog(null);
            if(status == JFileChooser.APPROVE_OPTION)
            {
                File selectedFile = fileChooser.getSelectedFile();
                String filename = selectedFile.getPath();
                String[] pathName = filename.split("CSC285_Project");
                photo = pathName[1];
            }
        }
        
    }
    /**
     * Creates a single Action listener for both buttons that will send it to
     * different tables depending on which button was pressed.
     */
    private class SubmitButtonActionListener implements ActionListener
    {

        private String tableName;

        /**
         * Constructor for the Actionlistener that allows me to put a String
         * representing what table I want the information to go to.
         * 
         * @param table 
         */
        public SubmitButtonActionListener(String table)
        {
            this.tableName = table;
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            // First validates the information to see if it can be put into the
            // table.
            String validate = CheckValidInput();
            if (!validate.equalsIgnoreCase("GOOD"))
            {
                JOptionPane.showMessageDialog(null, validate);
            } else
            {

                // Create a named constant for the URL.
                // NOTE: This value is specific for Java DB.
                final String DB_URL = "jdbc:derby:ARGDB;create=false";

                try
                {
                    // build string
                    String statment = ("INSERT INTO " + tableName + "_Table VALUES ( "
                            + "'" + uniqId + "', "
                            + "'" + engTitle + "', "
                            + "'" + japTitle + "', "
                            + "'" + description + "', "
                            + "'" + numVol + "', "
                            + "'" + genera + "', "
                            + "'" + artist + "', "
                            + "'" + photo + "' )");
                    // Create a connection to the database.
                    Connection conn =
                            DriverManager.getConnection(DB_URL);

                    // Create SQL Statment
                    Statement stmt = conn.createStatement();

                    // Insert row 
                    stmt.execute(statment);

                    // Close the connection.
                    conn.close();

                    FileWriter fwriter = new FileWriter(tableName + "File.txt", true);
                    PrintWriter outputFile = new PrintWriter(fwriter);
                    outputFile.println(statment);
                    outputFile.close();

                } catch (Exception ex)
                {
                    System.out.println("ERROR: " + ex.getMessage());
                }
            }
        }
    }
}
